import { Button, Card, message, Popconfirm, Switch, Table } from 'antd';
import { useEffect, useState } from 'react';

import scheduleService from '@/api/services/stars/scheduleService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { useRouter } from '@/router/hooks';
import { pagination } from '@/utils/pagination';
import { hasPermission } from '@/utils/permission';

import { ScheduleModal } from './schedule-modal';
import ScheduleSearchForm, { SearchForm } from './search-form';
import { ScheduleType } from './type';

import { ListData, ModalProps } from '#/entity';
import { JobGroupTypeMapText, misfirePolicyMapText, ScheduleStatus } from '#/publicVariable';

export default function Schedule() {
  const { push } = useRouter();
  const [tableData, setTableData] = useState<ListData<ScheduleType>>();
  const [searchData, setSearchData] = useState<SearchForm>({
    take: 10,
    page: 1,
  });
  useEffect(() => {
    if (hasPermission('QUARTZ:SYS_JOB:READ')) {
      scheduleService.getScheduleList(searchData).then((res) => {
        setTableData(res);
      });
    }
  }, [searchData]);

  const columns = [
    { title: '任务编号', dataIndex: 'jobId', width: 90 },
    {
      fixed: 'left' as const,
      title: '任务名称',
      dataIndex: 'jobName',
      width: 90,
    },
    {
      width: 90,
      title: '任务组名',
      dataIndex: 'jobGroup',
      render: (_, record) => {
        return JobGroupTypeMapText[record.jobGroup];
      },
    },
    {
      width: 340,
      title: '调用目标字符串',
      dataIndex: 'invokeTarget',
    },
    { width: 340, title: 'cron执行表达式', dataIndex: 'cronExpression' },

    {
      title: '执行策略',
      dataIndex: 'misfirePolicy',
      width: 120,
      render: (status) => {
        return misfirePolicyMapText[status] || '';
      },
    },
    {
      title: '是否允许并发',
      dataIndex: 'concurrent',
      width: 120,
      render: (status) => {
        switch (status) {
          case '0':
            return '允许';
          case '1':
            return '禁止';
          default:
            return '';
        }
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center' as const,
      width: 90,
      render: (status, record) => (
        <Switch
          checked={status === ScheduleStatus.ENABLE}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={() => onStatusChange(record)}
        />
      ),
    },
    {
      fixed: 'right' as const,
      title: <div style={{ marginRight: '55px' }}>操作</div>,
      align: 'right' as const,
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('QUARTZ:SYS_JOB:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="修改该张横幅信息">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('QUARTZ:SYS_JOB:DELETE') && (
            <Popconfirm
              title={`确定要删除任务 ${record.jobName} 吗？`}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
          {hasPermission('QUARTZ:SYS_JOB:UPDATE') && (
            <Popconfirm
              title={`确定要运行任务 ${record.jobName} 吗？`}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onRunOnce(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="运行一次">
                <Iconify icon="material-symbols:cycle" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
          {hasPermission('QUARTZ:SYS_JOB:READ') && (
            <TipIconButton
              tipText={`查看任务 ${record.jobName} 的日志`}
              onClick={() => {
                push(`/monitor/sys-job-log/${record.jobId}`);
              }}
            >
              <Iconify icon="material-symbols:acute" size={22} className="text-error" />
            </TipIconButton>
          )}
        </div>
      ),
    },
  ];
  const [scheduleModalProps, setScheduleModalProps] = useState<ModalProps<ScheduleType>>({
    title: '新增',
    show: false,
    onOk: () => {
      setScheduleModalProps((prev) => ({
        ...prev,
        show: false,
      }));
      setSearchData((prev) => ({ ...prev }));
    },
    onCancel: () => {
      setScheduleModalProps((prev) => ({
        ...prev,
        show: false,
      }));
    },
    formValue: {},
  });
  const onCreate = () => {
    setScheduleModalProps((prev) => ({
      ...prev,
      title: '新增',
      show: true,
      formValue: { misfirePolicy: 1, concurrent: 1, status: '0' },
    }));
  };
  const onEdit = (record: ScheduleType) => {
    setScheduleModalProps((prev) => ({
      ...prev,
      title: '修改',
      show: true,
      formValue: {
        ...record,
        concurrent: Number(record.concurrent),
      },
    }));
  };
  const onDelete = (record) => {
    if (tableData?.data.length === 1) {
      scheduleService.deleteSchedule(record.jobId!).then((res) => {
        if (res > 0) {
          message.success('删除成功');
        }
        setSearchData({ page: searchData.page - 1, take: searchData.take });
      });
    } else {
      scheduleService.deleteSchedule(record.jobId!).then((res) => {
        if (res > 0) {
          message.success('删除成功');
        }
        setSearchData({ ...searchData });
      });
    }
  };
  const onStatusChange = (record: ScheduleType) => {
    if (record.status === ScheduleStatus.ENABLE) {
      scheduleService.disable(record.jobId).then((res) => {
        if (res > 0) {
          message.success(`任务 ${record.jobName} 禁用成功`);
        }
        setSearchData({ ...searchData });
      });
    } else {
      scheduleService.enable(record.jobId).then((res) => {
        if (res > 0) {
          message.success(`任务 ${record.jobName} 启用成功`);
        }
        setSearchData({ ...searchData });
      });
    }
  };
  const onOk = (values: SearchForm) => {
    setSearchData({ take: 10, page: 1, ...values });
  };
  const onReset = () => {
    setSearchData({ page: 1, take: 10 });
  };
  const onRunOnce = (record) => {
    scheduleService.runOnce(record.jobId).then((res) => {
      if (res > 0) {
        message.success(`任务 ${record.jobName} 运行成功`);
      }
      // setSearchForm({ ...searchForm });
    });
  };
  return (
    <div>
      <ScheduleSearchForm onOk={onOk} onReset={onReset} />
      <br />
      <Card
        title="定时任务"
        extra={
          <div>
            {hasPermission('QUARTZ:SYS_JOB:CREATE') && (
              <Button
                type="primary"
                // disabled={!hasPermission('SECURITY:USER:CREATE')}
                onClick={onCreate}
              >
                新增
              </Button>
            )}
          </div>
        }
      >
        <Table
          size="small"
          rowKey="jobId"
          columns={columns}
          dataSource={tableData?.data}
          pagination={pagination({
            page: searchData, onPageChange: (page, rows) => {
              setSearchData((prev) => ({
                ...prev,
                page,
                take: rows,
              }));
            }, count: tableData?.count
          })}
        />
        <ScheduleModal {...scheduleModalProps} />
      </Card>
    </div>
  );
}
